package com.boat.framework.common.thread.context;

import java.net.InetAddress;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.MDC;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 日志上下文
 * 
 * @author 周江
 *
 */
@Slf4j
public class LogContext {
	public static final String KEY_TRACE_ID = "traceId";
	public static final String KEY_LOCAL_IP = "localIp";

	private static String LOCAL_IP;

	static {
		try {
			InetAddress addr = InetAddress.getLocalHost();
			LOCAL_IP = addr.getHostAddress();
		} catch (Exception ex) {
			log.warn("获取本地ip出错。错误原因：{}", ex.getMessage());
		}
	}

    private LogContext() {
		
	}

	// 开启线程时调用
	public static void newLogContext(String trackId) {
		if (StrUtil.isBlank(trackId)) {
			long newTrackId = IdUtil.getSnowflakeNextId();
			trackId = String.valueOf(newTrackId);
		}
		setTrackId(trackId);
		setLocalIp(LOCAL_IP);
	}

	public static void setTrackId(String trackId) {
		MDC.put(KEY_TRACE_ID, trackId);
	}

	public static String getTrackId() {
		return MDC.get(KEY_TRACE_ID);
	}

	public static void setLocalIp(String localIp) {
		MDC.put(KEY_LOCAL_IP, localIp);
	}
	
	public static String getLocalIp() {
		return MDC.get(KEY_LOCAL_IP);
	}

	public static boolean isEmptyOfTrackId() {
		return StrUtil.isBlank(getTrackId()) ? true : false;
	}
	
	public static void clear() {
		if (log.isDebugEnabled()) {
			log.debug("清理日志上下文信息");
		}
		MDC.remove(KEY_TRACE_ID);
	}

	//------复制和恢复上下文
	public static Map<String, String> getCopyOfContextMap(){
		Map<String, String> contextMap = new HashMap<>(4);
		contextMap.put(KEY_TRACE_ID, getTrackId());
		contextMap.put(KEY_LOCAL_IP, getLocalIp());
		return contextMap;
	}
	
	public static void setContextMap(Map<String, String> contextMap) {
		setTrackId(contextMap.get(KEY_TRACE_ID));
		setLocalIp(contextMap.get(KEY_LOCAL_IP));
	}
}
